package com.xiaoxu.privatechat.util;

import com.xiaoxu.privatechat.constant.SessionConstant;
import com.xiaoxu.privatechat.entity.admin.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author xiaoxu
 * @description session统一操作工具类
 * @date 2023/2/13
 */
public class SessionUtil {

    /**
     * @return HttpServletRequest
     * @description 获取请求request
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes == null ? null : attributes.getRequest();
    }

    /**
     * @return HttpSession
     * @description 获取session
     */
    public static HttpSession getSession() {
        HttpServletRequest request = getRequest();
        if (request != null) {
            return request.getSession();
        }
        return null;
    }

    /**
     * @param key key值
     * @return Object
     * @description 获取指定键的值
     */
    public static Object get(String key) {
        HttpSession session = getSession();
        if (session != null) {
            return session.getAttribute(key);
        }
        return null;
    }

    /**
     * @param key    key值
     * @param object 对象
     * @description 设置session值
     */
    public static void set(String key, Object object) {
        HttpSession session = getSession();
        if (session != null) {
            session.setAttribute(key, object);
        }
    }

    /**
     * @return User
     * @description 获取当前登录的用户
     */
    public static User getLoginedUser() {
        HttpSession session = getSession();
        if (session != null) {
            Object attribute = session.getAttribute(SessionConstant.SESSION_USER_LOGIN_KEY);
            return attribute == null ? null : (User) attribute;
        }
        return null;
    }
}
